# encoding:utf-8
#qpy:console
import my_importer
my_importer.myImport("myTools")
from myTools import * 
ccb =[
    {
        "phone": "13233701306",
        "headers": {
            "X-CSRF-TOKEN": "",
            "X-XSRF-TOKEN": "",
            "User-Agent": "",
            "cookie": ""
            },
        "ccb" : 0,
        "state": False,
        "time": "2021年09月07日 13时20分21秒"
    } 
]

myDict = {
    "主会场":"zhc",
    "消保专区(答题)":"xbzq_dt",
    "消保专区(眼力)":"xbzq_yl",
    "消保专区(拼图)":"xbzq_pt",
    "跨境专区":"kjzq",
    "银发专区":"yfzq",
    "裕农专区":"ynzq",
    #"商户专区":"shzq",
    "答题有礼":"dtyl"
    }
def init(): 
    #初始化
    global fileName
    fileName = "ccbUrl.json"
    global ccbUrl
    ccbUrl = getFile(fileName)
    ccbUrl = getccbUrl(ccbUrl)
    global questins_fileName      
    questins_fileName = "questions.json"
    global questions
    questions = getFile(questins_fileName)
    fileName = "ccb.json"
    global ccb
    ccb = getFile(fileName)
    global logFileName
    logFileName = "ccb.log"
     
def main(run = False):
    
    init()
    #代码开始运行
    
    updateState = False
    msg = "签到开始\n" 
    myCCBList = []
    for index in range(len(ccb)):
        ccbDict = {
        	    "ccb":ccb[index],
        	    "ccbUrl":ccbUrl,
        	    "questions":questions
        	}       	
        myCCBList.append(CCB(ccbDict))
    #依次登录
    for index in range(len(myCCBList)):        
        myCCB = myCCBList[index]
        updateState = updateCCB(myCCB)
        ccb[index] = myCCB.ccb
    #登录成功更新ccb.json  
    if updateState == True:
        if update(fileName,ccb) == False:
            update(fileName,ccb)
        updateState = False
    for index in range(len(myCCBList)):
        
        myCCB = myCCBList[index]
        myCCB1 = myCCBList[(index+1)%len(myCCBList)]            
        
        myCCB.test()
        msg += "\n\n用户:" + myCCB.ccb["phone"] + "  \n\n时间:" + getTime()           
        msg += "\n签到时间:" + myCCB.ccb["time"]                   
        if run == True or time.time() > getTime(myCCB.ccb["time"]):                
            for key in myDict: 
                if run == False and myCCB.ccb["state"].get(myDict[key]) == True:
                    break        
                #判断活动是否过期
                try:
                    #分享
                    ident = myCCB.getIdent(myDict[key])           
                    myCCB1.fx(myDict[key],ident)
        
                    text = ""
                    if myCCB.huoDongIsOK(myDict[key]) == True:
                        text =  eval(f"myCCB.{myDict[key]}()")
                    else:
                        text = "活动已结束！"
                    msg += f"\n\n{key}:" + text
                    myCCB.ccb["state"][myDict[key]] = True
                    updateState = True
                                 
                except Exception as e:
                    msg +=f"\n\n{key}有异常发生:" + traceback.format_exc()                                
        #返回数据处理  
        msg += f"\n总共获得cc豆:{int(myCCB.getCC())-int(myCCB.ccb['ccb'])}"
        msg += f"\ncc豆总数:{myCCB.getCC()}"                   
        ccb[index] = myCCB.ccb
    if updateState == True:
        push(msg)
        update(fileName,ccb)                         
        update(logFileName,log["log"])  
    myPrint(msg)
    
#处理ccbUrl
def getccbUrl(ccbUrl):
    for key in ccbUrl:
        dict_a = ccbUrl[key]
        host = dict_a["host"]
        url1 = dict_a["url+"]
        title = dict_a["title"]
        for key1 in dict_a:
            if key1 not in ["host","url+","title"]:
                dict_a[key1]["url"] = dict_a[key1]["url"].replace("{host}",host).replace("{url+}",url1)
                dict_a[key1]["title"] = dict_a[key1]["title"].replace("{title}",title)
    return ccbUrl
#登录以及更新ccb
def updateCCB(myCCB):
    updateState = False      
    print("用户:" + myCCB.ccb["phone"])
    if myCCB.cookieIsOK() == False:
        if myCCB.login() == True:
            updateState = True
        else:
            print("登录失败！")
            return False
    day_time = float(time.mktime(datetime.date.today().timetuple()))
    if (getTime(myCCB.ccb["time"]) - day_time) < 0 :
        myCCB.ccb["time"] = getTime(random.uniform(day_time+9*3600,day_time+12*3600))
        myCCB.ccb["ccb"] = myCCB.getCC()
        myCCB.ccb["state"] = {}
        for key in myDict: 
            myCCB.ccb["state"][myDict[key]] = False
        updateState = True
    return updateState

class CCB(): 

    cc = 0
    num = 0
    session = {}
    def __init__(self,myDict):
        for key,values in myDict.items():
            setattr(self,key,values)
        self.session = requests.session()
        self.session.headers.update(self.ccb["headers"])
        self.num = 0
        self.cc = self.ccb["ccb"]
        
    	                                                       
    def cookieIsOK(self):
        try:
            url = self.ccbUrl["zhc"]["yzUrl"]
            html = self.myRequests(url,"html")
            if html.status_code != 200:
                myPrint("session失效")                
                return False
            else:
                myPrint(html.json())
                if html.json().get("status") == "fail":
                    myPrint("session失效")
                    return False
                else:
                    return True
        except Exception as e:
            myPrint("session失效:" + traceback.format_exc())
            return None
    #活动是否过期
    def huoDongIsOK(self,key):
        myUrl = self.ccbUrl[key]
        url = myUrl["dateUrl"]
        endTime = int(self.myRequests(url,"end_time"))
        if time.time() < endTime:
            return True
        else:
            return False
    #登录
    def login(self):
        myUrl = self.ccbUrl["login"]
        url = myUrl["zyUrl"]
        self.session.close()
        self.session = requests.session()
       
        self.session.headers = {
                "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/89.0.4389.116 Safari/534.24 XiaoMi/MiuiBrowser/15.3.15"
            	}
        html = self.myRequests(url,"html")
        pattern = re.compile(r"[0-9a-zA-Z]{40}")
        data = pattern.findall(html.text)
        csrf = data[0]      
        n = 0
        while True:
            n +=1
            url = myUrl["tpUrl"]
            response = self.myRequests(url,"html")
            
            code = CSF("getCaptcha",response.content)       
            url = myUrl["dxUrl"]
            self.session.headers["X-CSRF-TOKEN"] = csrf
            url["data"] = {
            	    "mobile":self.ccb["phone"],
            	    "captcha":code
            	    }
            now = time.time()               
            myJson = self.myRequests(url)
            myPrint(myJson)
            if myJson["status"] == "success":
                url = myUrl["dlUrl"]
                code = ""
                while True:                
                    dict_a = CSF("getSMS")
                    if  dict_a["time"] > now:                    
                        code = dict_a["smsKey"]                    
                        break
                    time.sleep(10)                   
                url["data"] = {
            	        "phone":self.ccb["phone"],
            	        "code":code
            	        }
                myPrint(url["data"])
                myJson = self.myRequests(url)
                myPrint(myJson)
                
                cookie  = requests.utils.dict_from_cookiejar(self.session.cookies)              
                self.session.headers["X-XSRF-TOKEN"] = cookie["XSRF-TOKEN"]
                cookie = json.dumps(cookie).replace('{"','').replace('"}',"").replace('": "',"=").replace('", "',";")      
                self.session.headers["cookie"] = cookie      
                self.ccb["headers"] = self.session.headers
                return True
            elif n > 1:
                myPrint("错误次数超过2次")
                return False
    #更新questions.json文件
    def updateQuestions(self,questions):  
        #把questions按id顺序排列
        list_a = sorted(questions)
        dict_b = {}
        for index in range(len(list_a)):
            dict_b[list_a[index]] = questions[list_a[index]]
        questions = dict_b
        update(questins_fileName,questions)
    
    #列表访问
    def callList(self,list_a,urlList,func):
        for index in range(len(list_a)):
            for i in range(len(urlList)):
                time.sleep(1.5)                
                func(urlList[i],list_a[index])
                data = self.myRequests(urlList[i])
                if isinstance(data,dict):
                    myPrint(data)
                if data["status"] == "fail" or data["message"] == "已完成任务":
                    time.sleep(1.5)
                    break             
                
    #循环访问
    def callLoop(self,url,remain_num):
        msg = ""       
        while remain_num > 0:
            data = self.myRequests(url)
            if isinstance(data,dict):
           	     myPrint(data)
            message = findDict(data,"message")[0]
            msg += message
            prizename = findDict(data,"prize_name")[0] + findDict(data,"prizename")[0]
            if prizename != None and prizename != "":
                msg += f"({prizename}) "
            else:
                msg += "(未中奖!) "
            time.sleep(3)   
            remain_num -=1
        return msg
    def chouJiang(self,myUrl,key):
        time.sleep(3)
        message = ""
        url = myUrl["cjcsUrl"]
        remain_num = int(self.myRequests(url,key))        
        myPrint(f"剩余抽奖次数:{remain_num}")
        while remain_num > 0:
            url = myUrl["cjUrl"]
            message += self.callLoop(url,remain_num)
            url = myUrl["cjcsUrl"]
            remain_num = int(self.myRequests(url,key)) 
        msg = f"\n抽奖:{message}获得" + self.getCC("add") + "CC豆" 
        return msg
    def huoDong(self,myUrl,key,func):
        time.sleep(3)
        url = myUrl["hdlbUrl"]    
        taskList = self.myRequests(url,key)
        valueList = []
        urlList = []       
        url = myUrl.get("hdtjUrl")
        urlList.append(url)        	    
        url = myUrl.get("hdlqUrl")
        if url != None:
            urlList.append(url)
        self.callList(taskList,urlList,func)         	
        msg = "\n活动:获得" + self.getCC("add") + "CC豆" 
        return msg
    def daTi(self,myUrl,key):
        questions = self.questions            
        msg = ""
        url = myUrl["dtcsUrl"]
        remain_num = int(self.myRequests(url,key))
        myPrint(f"剩余答题次数:{remain_num}")
        msg += "\n答题:"
        #获取levelId 
        url = myUrl["idcxUrl"]
        data = self.myRequests(url,"level")
        if isinstance(data,list):
            levelId = data[0]
        else:
            levelId = data                                     
        while remain_num > 0:
            time.sleep(3)               
            url = myUrl["hqwtUrl"]
            url["data"]["id"] = levelId 
            question = self.myRequests(url,"data")            
            myPrint(question)
            
            options = question["options"]
            questionId = question["questionId"]
            url = myUrl["datjUrl"]
            while True:
                time.sleep(3)
                url["data"]["levelId"] = levelId
                url["data"]["id"] = questionId
                
                if questions.get(questionId) == None:
                    list_a = ["对","不正确","否","不可以"]
                    #答案选最长的
                    lens = 0
                    for index in range(len(options)):
                        if len(options[index]["option"]) > lens:
                            url["data"]["options"] =  options[index]["id"]
                            lens = len(options[index]["option"])
                    for index in range(len(options)):
                        if options[index]["option"] in list_a:
                            url["data"]["options"] =  options[index]["id"]
                                            
                else:
                    url["data"]["options"] =  questions.get(questionId)["answerId"]
                myPrint(url["data"])
                data = self.myRequests(url)
                myPrint(data)
                rightId = data["data"]["rights"][0]                
                
                for index in range(len(options)):
                    if options[index]["id"] == rightId:
                        answer = options[index]["option"]
                dict_a = {
                    "questionId" :questionId,
                    "question": question["title"],
                    "answerId": rightId,
                    "answer": answer          
                     }
                if questions.get(questionId) == None:                
                    questions[questionId] = dict_a
                    msg += "错误 "
                    self.updateQuestions(questions)
                elif questions.get(questionId)["answerId"] != rightId :
                    questions[questionId] = dict_a
                    self.updateQuestions(questions)
                    msg += "错误 "
                else:
                    msg += "正确 "
                if data["data"]["next"] == []:
                    remain_num -= 1
                    break
                else:
                    question = data["data"]["next"]
                    options = question["options"]
                    questionId = question["questionId"]
           
        return msg
    #主会场得CC豆    
    def zhc(self):        
        msg = ""
        myUrl = self.ccbUrl[sys._getframe().f_code.co_name]
        #财富值签到
        url = myUrl["cfzqdUrl"]
        data = self.myRequests(url)
        myPrint(data)
        if data["status"] == "fail":
           #pass
           return "已签到！"
        
        #每天领取cc豆
        url = myUrl["lqCCUrl"]
        data = self.myRequests(url)
        myPrint(data)
        #财富值做活动
        def func(url,dict_a):
            url["data"]= {
           	"id": dict_a["id"]
           	}
       	    myPrint(dict_a["show_set"]["name"])
        key = "task"
        msg += self.huoDong(myUrl,key,func)
        #升级小镇    
        url = myUrl["cfzslUrl"]
        data = self.myRequests(url,"data")
        url = myUrl["sjUrl"]           
        data = self.myRequests(url)
        return msg
           
    #银发专区得CC豆    
    def yfzq(self):
        msg = ""
        myUrl = self.ccbUrl[sys._getframe().f_code.co_name]
        url = myUrl["zyUrl"]        
        data = self.myRequests(url)        
        choiJiang_key = "remain_num"           
        msg += self.chouJiang(myUrl,choiJiang_key)
        return msg
    #裕农专区得CC豆    
    def ynzq(self):
        msg = ""
        myUrl = self.ccbUrl[sys._getframe().f_code.co_name]
        url = myUrl["zyUrl"]        
        data = self.myRequests(url)        
        choiJiang_key = "remain_num"           
        msg += self.chouJiang(myUrl,choiJiang_key)
        return msg
    #商户专区得CC豆    
    def shzq(self):
        msg = ""
        myUrl = self.ccbUrl[sys._getframe().f_code.co_name]
        url = myUrl["zyUrl"]        
        data = self.myRequests(url) 
        #商户专区做活动
        def func(url,dict_a):
            url["data"]= {
           	"id": dict_a["id"]
           	}
       	    myPrint(dict_a["show_set"]["name"])
        key = "task"
        msg += self.huoDong(myUrl,key,func)               
        choiJiang_key = "remain_num"           
        msg += self.chouJiang(myUrl,choiJiang_key)
        return msg
    #消保专区(答题)得CC豆    
    def xbzq_dt(self):
        msg = ""
        myUrl = self.ccbUrl[sys._getframe().f_code.co_name]
        daTi_key = "answer_num"
        choiJiang_key = "remain_num"           
        msg += self.daTi(myUrl,daTi_key)
        msg += self.chouJiang(myUrl,choiJiang_key)
        return msg
        
    #跨境专区得CC豆    
    def kjzq(self):
        msg = ""
        myUrl = self.ccbUrl[sys._getframe().f_code.co_name]
        daTi_key = "answer_num"
        choiJiang_key = "remain_num"           
        msg += self.daTi(myUrl,daTi_key)
        msg += self.chouJiang(myUrl,choiJiang_key)
        return msg
        
    #消保专区(眼力)得CC豆    
    def xbzq_yl(self):
        msg = ""
        myUrl = self.ccbUrl[sys._getframe().f_code.co_name]
        #答题次数查询
        url = myUrl["dtcsUrl"]
        remain_num = int(self.myRequests(url,"remain_num"))
        myPrint(f"剩余答题次数:{remain_num}")
        if remain_num == 0:
            msg +="答题次数不足！"
        
        msg += "\n答题:"
        while remain_num > 0:        
            url = myUrl["ksdtUrl"]    
            data = self.myRequests(url)
            url = myUrl["hqwtUrl"] 
            
            myList = self.myRequests(url,"data")
            answerId = ""
            time.sleep(6)
            for index in range(len(myList)):            
                questionId = myList[index]["id"]
                if questionId <= 670:
                    if answerId == "":
                        answerId = answerId + str(questionId)
                    else:
                        answerId = answerId + "," +  str(questionId)
            url = myUrl["datjUrl"]               
            data = {
                "answerId":answerId
                }
            url["data"] = data
            data = self.myRequests(url)
            status = data["status"]
            if status == "success":
                msg += "正确 "
            else:
                msg += "错误 "
            myPrint(data)
            time.sleep(10)
            
            remain_num -= 1
            
        choiJiang_key = "draw_remain_num"                   
        msg += self.chouJiang(myUrl,choiJiang_key)
          	
        return msg
    
    #消保专区(拼图)得CC豆    
    def xbzq_pt(self):
        msg = ""
        myUrl = self.ccbUrl[sys._getframe().f_code.co_name]
        #答题次数查询
        url = myUrl["dtcsUrl"]
        remain_num = int(self.myRequests(url,"remain_num"))
        myPrint(f"剩余答题次数:{remain_num}")
        if remain_num == 0:
            msg +="答题次数不足！"
      
        msg += "\n答题:"
        while remain_num > 0:
            time.sleep(5)
            url = myUrl["ksdtUrl"]    
            data = self.myRequests(url)
        
            url = myUrl["hqwtUrl"]   
            data = self.myRequests(url)
            #偏移量
            data["data"]["len0"] = 14
            data = CSF("xiangSi",data["data"])
            list_a = data
            sort = ""
            for index in range(len(list_a)):
                sort += "N" + str(list_a[index])
                if index < len(list_a)-1:
                    sort += ","    
            print(sort)
            time.sleep(20)
            url = myUrl["datjUrl"]               
            url["data"]["sort"] = sort
            data = self.myRequests(url)
            status = data["status"]
            if status == "success":
                msg += "正确 "
            else:
                data = self.myRequests(url)
                msg += "错误 "
            myPrint(data)
            time.sleep(5)        
            remain_num -= 1
        
        choiJiang_key = "draw_remain_num"                   
        msg += self.chouJiang(myUrl,choiJiang_key)
          	
        return msg          
    
    #签到有理得cc豆   
    def qdyl(self):
        msg = ""
        myUrl = self.ccbUrl[sys._getframe().f_code.co_name]
        url = myUrl["zyUrl"]
        data = self.myRequests(url)
        url = myUrl["qdUrl"]
        data = self.myRequests(url)
        msg += "获得" + self.getCC("add") + "CC豆" 
        return msg    
    #答题有理得财富值   
    def dtyl(self):
        msg = ""
        myUrl = self.ccbUrl[sys._getframe().f_code.co_name]
        daTi_key = "answer_num"
        msg += self.daTi(myUrl,daTi_key)
        return msg    
    #获得ident
    def getIdent(self,key):
        myUrl = self.ccbUrl[key]
        if myUrl.get("fxcxUrl") != None:
            url = myUrl["fxcxUrl"] 
            ident = self.myRequests(url,"ident")
            return ident
        else:
            return None
        
    #互相分享
    def fx(self,key,ident):
        time.sleep(1)
        myUrl = self.ccbUrl[key]
        if myUrl.get("fxUrl") != None:
            url = myUrl["fxUrl"] 
            if url["type"] == "get":
                url["params"]["u"] = ident
            else:
                url["data"]["user_id"] = ident
            html = self.myRequests(url)
            return "分享成功！"
                
    def getCC(self,data=""):
        url = self.ccbUrl["zhc"]["ccbslUrl"]
        cc1 = self.myRequests(url,"remain_money")
        if data == "add":
            sl = str(int(cc1)-int(self.cc))
            self.cc = cc1
            return sl
        else:
            return cc1
    def myRequests(self,url,key=None):
        return myRequests(self.session,url,key)  
    
    def test(self):
        pass        
        #self.xbzq_pt()  
                                                
if __name__ == "__main__":
    try:
        #myPrint(main(True))
        #main()
        pass
    except Exception as e:
        push(str(e))
     
def main_handler(event, context):
   return main()